﻿using System.Linq;
using System.Threading.Tasks;
using QFramework;
using UnityEngine;

namespace ProjectMyFarmAndShe
{
    public class HarvestTool : ITool, IController
    {
        public string Name => "收获工具";
        public string Key => "HarvestTool";
        public ToolType Type => ToolType.Tool;
        public float UseBrawn => 1;

        /// <summary>
        /// 收获工具
        /// 收获完成后重置网格数据
        /// </summary>
        /// <param name="pos"></param>
        /// <param name="grids"></param>
        public void Use(Vector3Int pos, DynaGrid<GridData> grids)
        {
            var gridData = grids[pos.x, pos.y];

            if (gridData == null || gridData.PlantItem == null || gridData.PlantItem.State != SeedStates.Ripe)
            {
                return;
            }

            var plant = gridData.PlantItem;
            var plantCount = HarvestCount(plant);
            var success = HarvestPlant(plant,plantCount);

            if (!success)
            {
                MessagePanel.Default.AddMessage("背包满了,无法收获植物");
                return;
            }
            
            plant.ChangeHarvestIcon();
            
            var targetRectTransform = UIGameController.Default.ToolbarPanel.ToolbarItemTemplates.FirstOrDefault()
                .GetComponent<RectTransform>();
            var targetPos = Vector3.zero;
            if (RectTransformUtility.ScreenPointToWorldPointInRectangle(targetRectTransform,
                    targetRectTransform.position, Camera.main, out var wordPos))
            {
                targetPos = wordPos;
            }

            Global.Brawn.Value -= UseBrawn;
            AudioKit.PlaySound("resources://Harvest");
            
            //收获植物动画
            async Task HarvestAnima()
            {
                for (var i = 0; i < plantCount; i++)
                {
                    var spriteObj = new GameObject("IconSprite");
                    spriteObj.Position2D(plant.Position2D());
                    var sprite = spriteObj.AddComponent<SpriteRenderer>();
                    sprite.sortingLayerName = "OnGround";
                    sprite.sprite = plant.Sprite.sprite;
                
                    ActionKit.Sequence()
                        .Callback(() => { plant.BoxCollider2D.enabled = false; })
                        .Parallel(p =>
                        {
                            p.Lerp(1, 1.3f, 0.1f, (s) => { spriteObj.LocalScale(s, s, 1); })
                                .Lerp(spriteObj.PositionX(), spriteObj.PositionX() + 0.4f, 0.3f, (x) => { spriteObj.PositionX(x); })
                                .Lerp(spriteObj.PositionY(), spriteObj.PositionY() + 0.4f, 0.3f, (y) => { spriteObj.PositionY(y); });
                        })
                        .Delay(0.1f)
                        .Parallel(p =>
                        {
                            p.Lerp(spriteObj.PositionX(), targetPos.x, 0.1f, (x) => { spriteObj.PositionX(x); })
                                .Lerp(spriteObj.PositionY(), targetPos.y, 0.1f, (y) => { spriteObj.PositionY(y); });
                        })
                        .Callback(() =>
                        {
                            spriteObj.DestroySelfGracefully();

                        })
                        .StartCurrentScene();
                
                    await Task.Delay(200);
                }
                
                plant.DestroyGameObjGracefully();
                MessagePanel.Default.AddMessage($"收获{plantCount}个{plant.Data.Key}");
            }

            ActionKit.Task(HarvestAnima)
                .StartCurrentScene();
            
            gridData.ResetGrid();
        }

        /// <summary>
        /// 收获植物
        /// </summary>
        /// <param name="plant"></param>
        /// <returns>收获的植物名字</returns>
        bool HarvestPlant(PlantItem plant, int count)
        {
            if (plant.State == SeedStates.Ripe)
            {
                if (plant is PotatoPlantItem)
                {
                    Global.PotatoCount.Value += count;
                    return this.GetSystem<IToolbarSystem>().AddToolbarData("Potato", count);
                }
                else if (plant is TurnipPlantItem)
                {
                    Global.TurnipCount.Value += count;
                    return this.GetSystem<IToolbarSystem>().AddToolbarData("Turnip", count);
                }
                else if (plant is PinkRadishPlantItem)
                {
                    Global.PinkRadishCount.Value += count;
                    return this.GetSystem<IToolbarSystem>().AddToolbarData("PinkRadish", count);
                }
                else if (plant is GrapePlantItem)
                {
                    Global.GrapeCount.Value += count;
                    return this.GetSystem<IToolbarSystem>().AddToolbarData("Grape", count);
                    
                }
                else if (plant is BlueBerryPlantItem)
                {
                    Global.BlueBerryCount.Value += count;
                    return this.GetSystem<IToolbarSystem>().AddToolbarData("BlueBerry", count);
                }
                else if (plant is EggplantPlantItem)
                {
                    Global.EggplantCount.Value += count;
                    return this.GetSystem<IToolbarSystem>().AddToolbarData("Eggplant", count);
                }
            }

            return false;
        }

        /// <summary>
        /// 收获数量
        /// </summary>
        /// <param name="plant"></param>
        /// <returns></returns>
        int HarvestCount(PlantItem plant)
        {
            if (plant is PotatoPlantItem)
            {
                var ripeCount = Random.Range(2, 5 + 1);
                
                return ripeCount;
            }
            else if (plant is TurnipPlantItem)
            {
                var ripeCount = Random.Range(2, 4 + 1);
                return ripeCount;
            }
            else if (plant is PinkRadishPlantItem)
            {
                var ripeCount = Random.Range(2, 3 + 1);
                return ripeCount;
            }
            else if (plant is GrapePlantItem)
            {
                var ripeCount = Random.Range(1, 4 + 1);
                return ripeCount;
            }
            else if (plant is BlueBerryPlantItem)
            {
                var ripeCount = Random.Range(4, 7 + 1);
                return ripeCount;
            }
            else if (plant is EggplantPlantItem)
            {
                return 1;
            }

            return 0;
        }

        public IArchitecture GetArchitecture()
        {
            return Global.Interface;
        }
    }
}